package com.ctw.mapmycity.auth;

import org.apache.http.protocol.HTTP;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;

import com.ctw.mapmycity.Constants;
import com.ctw.mapmycity.client.RequestMethod;
import com.ctw.mapmycity.client.RestClient;
import com.facebook.Session;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

public class AuthenticatorUtil {

	public static final String ACC_USER_DATA_AUTH_TYPE = "AUTH_TYPE";

	private final Context mContext;

	public AuthenticatorUtil(Context context) {
		mContext = context;
	}

	public Bundle getAuthToken(Account account, String authTokenType, Bundle loginOptions) {
		Bundle result = new Bundle();
		Session fbSession = Session.getActiveSession();
		AccountManager am = AccountManager.get(mContext);		
		String password = am.getPassword(account);		

		if (!authTokenType.equals(Constants.AUTHTOKEN_TYPE)) {
			result.putString(AccountManager.KEY_ERROR_MESSAGE, "invalid authTokenType");
			return result;
		}
		
		LoginType loginType = LoginType.getTypeEnum(am.getUserData(account, Authenticator.ACC_USER_DATA_AUTH_TYPE));
		
		if (LoginType.FB.equals(loginType)) {
			
			if (fbSession != null && fbSession.isOpened()) {
				result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
				result.putString(AccountManager.KEY_ACCOUNT_TYPE, Constants.ACCOUNT_TYPE);
				result.putString(AccountManager.KEY_AUTHTOKEN, "");
				result.putString(AccountManager.KEY_AUTHENTICATOR_TYPES, LoginType.FB.getType());
				result.putParcelable("account", account);
				
				return result;
			}
			
		} else {
		
			result = callAuthService(account.name, password);
			String token = result.getString(AccountManager.KEY_AUTHTOKEN);
			
			if (token != null && !TextUtils.isEmpty(token)) {
				result.putParcelable("account", account);
				
				return result;
			}
			
			if (fbSession != null && fbSession.isOpened())
				fbSession.closeAndClearTokenInformation();
		}

		final Intent intent = new Intent(mContext, LoginActivity.class);
		intent.putExtra(LoginActivity.ARG_ACCOUNT_EMAIL, LoginType.FB.equals(loginType) ? "" : account.name);
		intent.putExtra(AccountManager.KEY_ERROR_CODE, result.getInt(AccountManager.KEY_ERROR_CODE));
		result.putParcelable(AccountManager.KEY_INTENT, intent);
		return result;
	}

	public Bundle callAuthService(final String email, final String password){
		final Bundle result = new Bundle();

		Thread thread = new Thread(new Runnable() {
			@Override
			public void run() {
				String response;
				String token = "";
				LoginType authType = LoginType.STANDARD;
				Integer status = Integer.valueOf(0);
				//
				try {
					
					String url = "account";
					
					com.ctw.mapmycity.model.Account acc = new com.ctw.mapmycity.model.Account(email, "", password, password, "");
					
					Gson gson = new Gson();
					JsonObject jo = new JsonObject();
					
					RestClient client = null;
//					client = new RestClient(url);
//					client.AddHeader("Accept", "application/json");
//					client.AddHeader(HTTP.CONTENT_TYPE, "application/json");
//					
//					client.AddParam("account", gson.toJsonTree(acc).toString());
//					client.Execute(RequestMethod.POST);
//					response = client.getResponse();
//					
//					acc = gson.fromJson(response, com.ctw.mapmycity.model.Account.class);

					if (acc != null){
					
	//					@QueryParam("email") String email, @QueryParam("token") String token
						client = new RestClient(url + "/auth");
						client.AddHeader("Accept", "application/json");
						client.AddHeader(HTTP.CONTENT_TYPE, "text/plain");
						
						client.AddParam("email", acc.getEmail());
						client.AddParam("token", acc.getPassword());
						
						client.Execute(RequestMethod.GET);
						response = client.getResponse();
	
						acc = gson.fromJson(response, com.ctw.mapmycity.model.Account.class);
						if (acc != null)
							token = acc.getToken();
					}
					
//					final RestClient client = new RestClient(NetworkUtilities.SERVER_IP + "/mmc_server/rest/restAuthService");
					
//					client.AddParam("email", email);
//					client.AddParam("password", password);
//					client.AddHeader("Accept", "application/json");
//
//					try {
//						Thread.currentThread().sleep(300);
//					} catch (InterruptedException e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					}
//
//					token = "test";
					
//					client.Execute(RequestMethod.GET);
//					response = client.getResponse();
//					status = client.getResponseCode();
//
//					if (status == 200){
//						JSONObject json = new JSONObject(response);
//						
//						token = json.getString("token");
//						authType = LoginType.getTypeEnum(json.getString("authType"));
//						status = json.getInt("status");
//
//						// error treatment 
//					}else {
//						token = "";
//					}

					//					token = "aodkaçskda"; 

				} catch (Exception e) {
					result.putInt(AccountManager.KEY_ERROR_CODE, AccountManager.ERROR_CODE_NETWORK_ERROR);	
				}

				result.putString(AccountManager.KEY_ACCOUNT_NAME, email);
				result.putString(AccountManager.KEY_ACCOUNT_TYPE, Constants.ACCOUNT_TYPE);
				result.putString(AccountManager.KEY_AUTHTOKEN, token);
				result.putString(AccountManager.KEY_AUTHENTICATOR_TYPES, authType == null ? LoginType.FB.getType() : authType.getType());
			}
		});

		try {
			thread.start();
			thread.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		return result;


		//		        	SoapObject request = new SoapObject("http://impl.ws.mapmycity.ctw.com/", "authenticate");       
		//	                
		//	                //Use this to add parameters
		//		        	request.addProperty("email", account.name);
		//		        	request.addProperty("password", password);
		//	
		//	                //Declare the version of the SOAP request
		//	                SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
		//	               
		//	                envelope.setOutputSoapObject(request);
		//	                envelope.dotNet = true;
		//	               
		//	                try {
		//	                      HttpTransportSE androidHttpTransport = new HttpTransportSE(NetworkUtilities.SERVER_IP + "/mmc_server/ws/authService?wsdl");
		//	                     
		//	                      //this is the actual part that will call the webservice
		//	                      androidHttpTransport.call("http://impl.ws.mapmycity.ctw.com/authenticate", envelope);
		//	                     
		//	                      // Get the SoapResult from the envelope body.
		//	                      SoapObject result = (SoapObject)envelope.bodyIn;
		//	
		//	                      if(result != null)
		//	                            authToken = result.getProperty(0).toString();
		//	                      else
		//	                            Toast.makeText(mContext, "No Response",Toast.LENGTH_LONG).show();
		//	                      
		//	                } catch (Exception e) {
		//	                      e.printStackTrace();
		//	                }
	}
}
